package se480.paf.filters.impl;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import se480.paf.filters.ActiveFilter;
import se480.paf.pipes.Item;
import se480.paf.pipes.Pipe;
import se480.paf.pipes.impl.Queue;
import se480.paf.stemming.Stemmer;

/**
 * This filter stems the words
 * 
 * Input:  List<String> of words
 * Output:  List<String> of words
 * 
 * @author mmichalak
 *
 */
public class StemWordsFilter implements ActiveFilter {
	
	static Logger logger = Logger.getLogger("StemWordsFilter");
	
	String name = "StemWordsFilter";
	int msSleep = 2000; // Default Thread sleep time
	
	public Pipe<Item> inPipe;
	public Pipe<Item> outPipe;

	Stemmer stemmer = new Stemmer(); // Strategy for the Stemmer
	
	@Override
	public void run() {
		try {
		      int i = 0;
		      while (true) {
		    	 if (!inPipe.isEmpty()) {
		    		 Item item = inPipe.removeItem();
		    		 process(item);
		    		 
		    	 }
		    	  
		    	 //StdOut.println(name + " wake: " + i++);
		         Thread.sleep(msSleep);

		      	}
	    } catch (InterruptedException e) {
	  	  //logger.debug(name + " interrupted.");
	    }
	    logger.debug(name + " exiting.");

	}

	@Override
	public void process(Item item) {
		long startTime = System.currentTimeMillis();
		 ArrayList<String> words = (ArrayList<String>)item.getItem();
		 logger.debug(name + " picked up " + item.getName());
		 
			ArrayList<String> stemmedWords = new ArrayList<String>();
			stemmer.reset();
			
			int totalWords = 0;
			for (String word : words) {
				totalWords += 1;
				stemmer.reset();
				stemmer.add(word.toCharArray(), word.length());
				stemmer.stem();
				stemmedWords.add(stemmer.toString());
			}

	    item.setItem(stemmedWords);
	    long endTime = System.currentTimeMillis();
	    item.addExecuteTimes(name + " - " + (endTime - startTime));
	    //logger.debug(stemmedWords);
	    
	    outPipe.addItem(item);
	}



	@Override
	public void setInPipe(Pipe<Item> pipe) {
		this.inPipe = pipe;
	}

	@Override
	public void setOutPipe(Pipe<Item> pipe) {
		this.outPipe = pipe;
	}


	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public void setSleep(int msSleep) {
		this.msSleep = msSleep;
	}

	@Override
	public int getSleep() {
		return this.msSleep;
	}

	@Override
	public Pipe<Item> getInPipe() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Pipe<Item> getOutPipe() {
		// TODO Auto-generated method stub
		return null;
	}

}
